// 风险等级枚举
export enum UserRiskLevel {
  R1 = 'R1',
  R2 = 'R2', 
  R3 = 'R3',
  R4 = 'R4',
  R5 = 'R5'
}

// 流动性偏好枚举
export enum LiquidityPreference {
  HIGH = '高流动性',
  MEDIUM_LOW = '中/低流动性'
}

// 性别枚举
export enum Gender {
  MALE = 'male',
  FEMALE = 'female'
}

// 用户相关类型
export interface User {
  id: string;
  name: string;
  email: string;
  phone?: string;
  avatar?: string;
  riskLevel: 'conservative' | 'moderate' | 'aggressive';
  investmentExperience: 'beginner' | 'intermediate' | 'advanced';
  totalAssets: number;
  createdAt: string;
}

// 投资组合类型
export interface Portfolio {
  id: string;
  userId: string;
  name: string;
  totalValue: number;
  totalReturn: number;
  totalReturnPercent: number;
  dayChange: number;
  dayChangePercent: number;
  allocations: Allocation[];
  createdAt: string;
  updatedAt: string;
}

export interface Allocation {
  id: string;
  assetType: 'stocks' | 'bonds' | 'etf' | 'crypto' | 'cash';
  symbol: string;
  name: string;
  quantity: number;
  currentPrice: number;
  totalValue: number;
  weight: number;
  dayChange: number;
  dayChangePercent: number;
}

// 市场数据类型
export interface MarketData {
  symbol: string;
  name: string;
  price: number;
  change: number;
  changePercent: number;
  volume: number;
  marketCap?: number;
  high52Week: number;
  low52Week: number;
}

// AI推荐类型
export interface Recommendation {
  id: string;
  type: 'buy' | 'sell' | 'hold' | 'rebalance';
  symbol: string;
  name: string;
  currentPrice: number;
  targetPrice?: number;
  confidence: number; // 0-100
  reasoning: string;
  riskLevel: 'low' | 'medium' | 'high';
  expectedReturn: number;
  timeHorizon: '1M' | '3M' | '6M' | '1Y' | '2Y+';
  createdAt: string;
}

// 风险评估类型
export interface RiskAssessment {
  id: string;
  userId: string;
  overallRisk: number; // 0-100
  portfolioRisk: number;
  marketRisk: number;
  concentrationRisk: number;
  volatilityRisk: number;
  recommendations: string[];
  assessmentDate: string;
}

// 交易记录类型
export interface Transaction {
  id: string;
  userId: string;
  portfolioId: string;
  type: 'buy' | 'sell';
  symbol: string;
  name: string;
  quantity: number;
  price: number;
  totalAmount: number;
  fees: number;
  status: 'pending' | 'completed' | 'failed';
  executedAt?: string;
  createdAt: string;
}

// 新闻和洞察类型
export interface MarketInsight {
  id: string;
  title: string;
  summary: string;
  content: string;
  category: 'market' | 'analysis' | 'news' | 'ai-insight';
  impact: 'positive' | 'negative' | 'neutral';
  relevantSymbols: string[];
  publishedAt: string;
  source: string;
}

// 分析报告类型
export interface AnalysisReport {
  id: string;
  userId: string;
  portfolioId: string;
  type: 'performance' | 'risk' | 'allocation' | 'monthly' | 'quarterly';
  title: string;
  summary: string;
  metrics: ReportMetric[];
  charts: ChartData[];
  recommendations: string[];
  generatedAt: string;
}

export interface ReportMetric {
  name: string;
  value: number | string;
  change?: number;
  benchmark?: number;
  description: string;
}

export interface ChartData {
  type: 'line' | 'bar' | 'pie' | 'area';
  title: string;
  data: any[];
  xAxis?: string;
  yAxis?: string;
}

// API响应类型
export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

// 应用状态类型
export interface AppState {
  user: User | null;
  portfolios: Portfolio[];
  selectedPortfolio: Portfolio | null;
  marketData: MarketData[];
  recommendations: Recommendation[];
  transactions: Transaction[];
  insights: MarketInsight[];
  loading: boolean;
  error: string | null;
}

// 风险等级配置类型
export interface RiskProfile {
  level: number;
  name: string;
  description: string;
  allocation: {
    stocks: number;
    bonds: number;
    cash: number;
  };
}

/**
 * 基金持仓信息
 */
export interface FundHolding {
  fund_code: string; // 基金代码
  fund_name: string; // 基金名称
  fund_type: string; // 基金类型
  holding_amount: number; // 持有金额
  holding_profit: number; // 持有收益
  holding_return_rate: string; // 持有收益率
  holding_shares: number; // 持有份额
  purchase_date: string; // 购买日期
  unit_net_value: number; // 单位净值
}

/**
 * 客户信息 - 新的客户数据结构
 */
export interface Customer {
  id: number; // 系统内部客户ID
  name: string; // 客户姓名
  account_balance: number; // 账户余额
  account_open_date: string; // 账户开户日期
  account_type: string; // 账户类型
  address: string; // 客户地址
  annual_income: number; // 年收入（数值形式）
  birth_date: string; // 出生日期
  credit_score: number; // 信用评分
  customer_level: string; // 客户等级
  education_level: string; // 教育水平
  email: string; // 电子邮箱
  employer: string; // 雇主/公司名称
  gender: string; // 性别
  id_number: string; // 身份证号码
  investment_experience: string; // 投资经验
  last_transaction_date: string; // 最后交易日期
  last_update_time: string; // 最后更新时间
  marital_status: string; // 婚姻状况
  occupation: string; // 职业
  phone_number: string; // 电话号码
  risk_level: string; // 风险等级
  total_investment: number; // 总投资金额
  total_profit: number; // 总收益
  total_return_rate: string; // 总收益率
  liquidity_preference: string; // 流动性偏好
  investment_goal: string; // 投资目标
  user_loss_warning: string; // 用户流失预警
  fund_holdings: FundHolding[]; // 基金持仓列表
  age_range: string; // 年龄范围
  annual_income_formatted: string; // 格式化后的年收入
  aum_scale: string; // 资产管理规模
  risk_preference: string; // 风险偏好
  trading_info: string; // 交易信息
  current_position: string; // 当前持仓配置（JSON字符串）
  recent_position_expiry: string; // 最近持仓到期信息
  session_id: string; // 会话ID
  risk_score: number; // 风险评分
  historical_returns: string; // 历史收益率（JSON字符串）
  average_holding_period: string; // 平均持有期
  trading_frequency: string; // 交易频率
  investment_timing: string; // 投资时机偏好
  loss_tolerance: string; // 亏损承受能力
  preferred_investment_types: string[]; // 偏好的投资类型
  financial_knowledge_level: string; // 金融知识水平
  compliance_status: string; // 合规状态
  preferred_contact_channel: string; // 偏好的联系渠道
  best_contact_time: string; // 最佳联系时间
  communication_frequency: string; // 沟通频率
  ai_summary: string; // AI生成的客户摘要（JSON字符串）,
  investment_strategy: number; // 客户匹配的策略ID
  override_investment_strategy?: number | null; // 用户手动选择的策略ID，覆盖推荐策略
}

// 会话ID生成规则：B端用户ID_C端用户ID
export const generateConversationId = (bUserId: string, cUserId: string): string => {
  return `${bUserId}_${cUserId}`;
};

// 从会话ID解析用户ID
export const parseConversationId = (conversationId: string): { bUserId: string; cUserId: string } => {
  const [bUserId, cUserId] = conversationId.split('_');
  return { bUserId, cUserId };
};    